package com.estronger.shopmanage.ui.batchpg;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.batchpg.BatchPgConfirmAdapter;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.ReturnMsgEntity;
import com.estronger.shopmanage.bean.batch.BatchPgListBean;
import com.estronger.shopmanage.bean.batch.DeliverPGListData;
import com.estronger.shopmanage.bean.batch.InstallPGListData;
import com.estronger.shopmanage.bean.batch.MeasurePGListData;
import com.estronger.shopmanage.manager.DataManager;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.utils.ConvertUtils;
import com.estronger.shopmanage.utils.CustomLinearLayoutManager;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.utils.ViewVisibilityOrGone;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.CircularProgress;
import com.estronger.shopmanage.view.SelectPeopleActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.NoDoubleClickUtils;
import com.soonfor.evaluate.tools.Tokens;
import com.soonfor.systemcodes.SystemCodePresenter;
import com.soonfor.systemcodes.SystemCodes;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;



/**
 * Created by Soonfor on 2017/5/17.
 * 批量派工确认界面
 */

public class BatchPgConfirmActivity extends BaseActivity
        implements View.OnClickListener, BatchPgConfirmAdapter.AdapterListener {

    private RelativeLayout rl_root;// 根布局view
    private Activity mContext;
    private LinearLayout ll_peple;
    private RelativeLayout rlfAssigned;//
    private TextView tvfAssignedT;//被指派人
    private TextView tvfAssigned;//被指派人
    private RecyclerView rvListView;
    private CircularProgress bar;
    private TextView empty_view;
    private Button btn_btch_confirm;//确认派工
    private List<BatchPgListBean> dataList;
    private BatchPgConfirmAdapter bpcAdapter;
    private CustomLinearLayoutManager cllManager;
    private int dataType = 0; //1-测量 2-送货 3-安装
    private String ids;//任务ids字符串
    private String assigneId = "";//被派工任务的id
    private String taskId = "0";//单个任务id,用于取设计师和安装员
    private boolean isAssignedViewHide = false;//选择设计师view是否已隐藏
    private ViewVisibilityOrGone viewVisibilityOrGone;//隐藏的动画
    // 初始化各个View
    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rl_root = (RelativeLayout) View.inflate(this, R.layout.activity_pg_batch_confirm, null);
        setContentView(rl_root);
        mContext = BatchPgConfirmActivity.this;
        ll_peple = rl_root.findViewById(R.id.ll_peple);
        rlfAssigned = rl_root.findViewById(R.id.rlfAssigned);
        tvfAssignedT = rl_root.findViewById(R.id.tvfAssignedT);
        tvfAssigned = rl_root.findViewById(R.id.tvfAssigned);
        rvListView = rl_root.findViewById(R.id.rv_batchs);
        bar = (CircularProgress) rl_root.findViewById(R.id.loding_view);
        empty_view = (TextView) rl_root.findViewById(R.id.empty_view);
        btn_btch_confirm = rl_root.findViewById(R.id.btn_btch_confirm);
        btn_btch_confirm.setOnClickListener(this);
        ids = getIntent().getStringExtra("data_ids");
        if(ids == null || ids.trim().equals("")){
            finish();
        }else {
            initSystemCode();
            if(ids.contains(",")){
                taskId = ids.substring(0, ids.indexOf(",")).trim();
            }else {
                taskId = ids.trim();
            }
            cllManager = new CustomLinearLayoutManager(mContext);
            rvListView.setLayoutManager(cllManager);
            bpcAdapter = new BatchPgConfirmAdapter(mContext);
            bpcAdapter.setAdapterListener(this);
            rvListView.setAdapter(bpcAdapter);
            rvListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
//                Util.closeKeyboard(ProductListActivity.this);
                    if (dy > 5) {
                        if (!isAssignedViewHide) {
                            if (viewVisibilityOrGone == null) {
                                viewVisibilityOrGone = new ViewVisibilityOrGone(ll_peple);
                            }
                            viewVisibilityOrGone.setCurrentMove(true);
                        }
                        isAssignedViewHide = true;
                    }
                    if (dy < -5) {
                        if (isAssignedViewHide) {
                            if (viewVisibilityOrGone == null) {
                                viewVisibilityOrGone = new ViewVisibilityOrGone(ll_peple);
                            }
                            viewVisibilityOrGone.setCurrentMove(false);
                        }
                        isAssignedViewHide = false;
                    }
                }
            });
            bar.setVisibility(View.VISIBLE);
            dataType = getIntent().getIntExtra("data_type", 0);
            if(dataType == 1) { tvfAssignedT.setText("设计师");}
            else if(dataType == 2) {tvfAssignedT.setText("送货员");}
            else if(dataType == 3) {tvfAssignedT.setText("安装员");}
            rlfAssigned.setOnClickListener(this);
            //获得数据
            loadData(ids);
        }
    }

    //初始取系统参数
    private boolean ifMultSelPeople = false;//选中派工人员是否可以多选
    private void initSystemCode() {
        if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("")) {
            new SystemCodePresenter(new SystemCodePresenter.CallBack() {
                @Override
                public void onSingle(int type, boolean isSuccess, String data, String fullmsg) {
                    if (type == 102){
                        if(isSuccess && data != null && data.equals("1")) {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("1");
                            ifMultSelPeople = true;
                        }else {
                            SystemCodes.getInstance().setCRM_DlvIstManCanSelMore("0");
                            ifMultSelPeople = false;
                        }
                    }
                }

                @Nullable
                @Override
                public void onMult(boolean isSuccess, String fullmsg) {

                }
            }).getOneSystemParams(Tokens.DSM_IFSHOWOTHERPOINT, 102, 0);
        }else {
            if (SystemCodes.getInstance().getCRM_DlvIstManCanSelMore().equals("1"))
                ifMultSelPeople = true;
            else
                ifMultSelPeople = false;
        }
    }
    //加载数据
    protected void loadData(final String ids) {
        if (!NetUtils.isNetworkConnected(this)) {
            Toast.show(this, "网络链接已断开！", 2000);
        } else {
            MyApplication.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    postRequest(ids);
                }
            }, 100);
        }
    }

    //请求批量派工任务数据
    public void postRequest(String ids) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        if (dataType == 1) {
            //测量任务待派工
            params.addBodyParameter("sf_action", "plgetplanmeasure");
            params.addBodyParameter("measureids", ids);
        } else if (dataType == 2) {
            //送货任务待派工
            params.addBodyParameter("sf_action", "plgetdlvassigninfo");
            params.addBodyParameter("dlvids", ids);
        } else if (dataType == 3) {
            //安装任务待派工
            params.addBodyParameter("sf_action", "plgetistinfo");
            params.addBodyParameter("dlvids", ids);
        }
        connect(params, NetManager.GETLIST_BATCHPG);
    }

    //批量派工确认
    public void postConfirmBatchPg(RequestParams params){
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        connect(params, NetManager.SAVE_BATCHPG);
    }

    @Override
    protected void onNetErorr(int code, String msg) {
        if (null != bar) bar.setVisibility(View.GONE);
        if (dataList.size() == 0) {
            empty_view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        String name = MyApplication.selectPeople;
        if (name != null) {
            tvfAssigned.setText(name + "");
            assigneId = MyApplication.selectID;
        }
    }

    @Override
    protected void onNetSuccess(int code, String result) {
        try {
            if (code == NetManager.GETLIST_BATCHPG) {//请求待确认数据
                List<BatchPgListBean> resultList = new ArrayList<>();
                String msg = "暂无待派工数据";
                try {
                    ReturnMsgEntity re = JsonUtil.returnMsgEntity(result);
                    if(re.getMsgcode() == 0 && re.getDataJson() != null) {
                        JSONArray ja = new JSONArray(re.getDataJson());
                        if (ja != null && ja.length() > 0) {
                            if (dataType == 1) {
                                for (int i = 0; i < ja.length(); i++) {
                                    BatchPgListBean listBean = new BatchPgListBean();
                                    listBean.setDatatype(1);
                                    MeasurePGListData measurePGListData = gson.fromJson(ja.getString(i), MeasurePGListData.class);
                                    listBean.setMeasure(measurePGListData);
                                    resultList.add(listBean);
                                }
                            } else if (dataType == 2) {
                                for (int i = 0; i < ja.length(); i++) {
                                    BatchPgListBean listBean = new BatchPgListBean();
                                    listBean.setDatatype(2);
                                    DeliverPGListData deliverPGListData = gson.fromJson(ja.getString(i), DeliverPGListData.class);
                                    listBean.setDeliver(deliverPGListData);
                                    resultList.add(listBean);
                                }
                            } else if (dataType == 3) {
                                for (int i = 0; i < ja.length(); i++) {
                                    BatchPgListBean listBean = new BatchPgListBean();
                                    listBean.setDatatype(3);
                                    InstallPGListData installPGListData = gson.fromJson(ja.getString(i), InstallPGListData.class);
                                    listBean.setInstall(installPGListData);
                                    resultList.add(listBean);
                                }
                            }
                        }
                    } else {
                        if (re != null) msg = re.getMsg();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    msg = e.getMessage();
                }
                if(dataList == null) dataList = new ArrayList<>();
                if (resultList.size() > 0) {
                    empty_view.setVisibility(View.GONE);
                    dataList.addAll(resultList);
                } else {
                    empty_view.setVisibility(View.VISIBLE);
                    empty_view.setText(msg);
                    Toast.show(mContext, msg, Toast.LENGTH_SHORT);
                }
                bpcAdapter.notifyDataSetChanged(dataList);
            }else if(code == NetManager.SAVE_BATCHPG){//确认派工
                ReturnMsgEntity reEntity = JsonUtil.returnMsgEntity(result);
                if (reEntity.getSuccess() && reEntity.msgcode==0) {
                    BatchPgActivity.isNeedUpdateView = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 2000);
                    AppDialog.showTaskingDialog(mContext, R.drawable.send_success, "任务派送成功").show();
                } else {
                    String msg = reEntity.getMsg();
                    if(msg.equals("")) msg = "任务派送失败";
                    AppDialog.showTaskingDialog(mContext, R.drawable.send_failure, msg).show();
                }
            }
        } catch (Exception ee) {
            ee.fillInStackTrace();
        }
        if (null != bar) bar.setVisibility(View.GONE);
    }


    /**
     * @param activity
     * @param dataType 1-测量 2-送货 3-安装
     * @param ids
     */
    public static void startTActivity(Activity activity, int dataType, String ids) {
        Intent intent = new Intent(activity, BatchPgConfirmActivity.class);
        intent.putExtra("data_type", dataType);
        intent.putExtra("data_ids", ids);
        activity.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.rlfAssigned){//选择被派工人
            if (NoDoubleClickUtils.isDoubleClick()) return;
            SelectPeopleActivity.open(mContext, dataType, taskId, ifMultSelPeople);
        }else if (v.getId() == R.id.btn_btch_confirm) {//确认派工
            if (NoDoubleClickUtils.isDoubleClick()) return;
            if(dataList == null || dataList.size() == 0){
                Toast.show(mContext,"暂无可派工确认的数据", Toast.LENGTH_LONG);
                return;
            }
            if(tvfAssigned.getText().toString().trim().equals("")){
                Toast.show(mContext, "请先选择" + tvfAssignedT.getText().toString(), Toast.LENGTH_SHORT);
                return;
            }
            if(TextUtils.isEmpty(assigneId)){
                Toast.show(mContext, tvfAssignedT.getText().toString() + "id为空，请重新选择", Toast.LENGTH_SHORT);
                return;
            }
            confirmPg();
        }
    }

    /**
     * 确认派工
     */
    private void confirmPg(){
        if(bar != null) bar.setVisibility(View.VISIBLE);
        boolean isNullDate = false;//是否存在预约时间为空的任务
        String exception = "";//是否报错, 报错的内容
        RequestParams params = new RequestParams();
        Gson gson = new Gson();
        if (dataType == 1) {
            //测量任务待派工
            params.addBodyParameter("sf_action", "plconfirmcondition");
            JSONArray jsonArray = new JSONArray();
            for (BatchPgListBean listBean : dataList){
                MeasurePGListData measure = listBean.measure;
                if(measure.getPlanmeasuredate().equals("")){
                    isNullDate = true;
                    break;
                }else {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("measureid", measure.getMeasureid());
                        jsonObject.put("ifassigndesigner", "1");
                        jsonObject.put("newplanmeasuredate", measure.getPlanmeasuredate());
                        jsonObject.put("newplandesignerid", assigneId);
                        jsonObject.put("firstdemand", measure.getFirstdemand());
                        jsonObject.put("measureitem", DataManager.batchMesureGoodsToJson(measure.getMeasureitem()));
                        jsonArray.put(jsonObject);
                    } catch (Exception e1) {
                        exception = ConvertUtils.formatNull(e1.getMessage());
                        if(exception.equals("")) exception = "设置请求参数出错";
                        break;
                    }
                }
            }
            params.addBodyParameter("measuredata", jsonArray.toString());
        } else if (dataType == 2) {
            //送货任务待派工
            params.addBodyParameter("sf_action", "pldlvassign");
            JSONArray jsonArray = new JSONArray();
            for (BatchPgListBean listBean : dataList){
                DeliverPGListData deliver = listBean.deliver;
                if(deliver.getPddate().equals("")){
                    isNullDate = true;
                    break;
                }else {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("dlvid", deliver.getDlvid());
                        jsonObject.put("dlvman", assigneId);
                        jsonObject.put("pddate", deliver.getPddate());
                        if(!deliver.getPidate().equals("")){
                            jsonObject.put("ifist", "1");
                            jsonObject.put("pidate", deliver.getPidate());
                        }else {
                            jsonObject.put("ifist", "0");
                        }
                        jsonObject.put("remark", deliver.getRemark());
                        jsonArray.put(jsonObject);
                    } catch (Exception e2) {
                        exception = ConvertUtils.formatNull(e2.getMessage());
                        if(exception.equals("")) exception = "设置请求参数出错";
                        break;
                    }
                }
            }
            params.addBodyParameter("dlvdata", jsonArray.toString());
        } else if (dataType == 3) {
            //安装任务待派工
            params.addBodyParameter("sf_action", "plistconfirmcondition");
            JSONArray jsonArray = new JSONArray();
            for (BatchPgListBean listBean : dataList){
                InstallPGListData install = listBean.install;
                if(install.getPidate().equals("")){
                    isNullDate = true;
                    break;
                }else {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("dlvid", install.getDlvid());
                        jsonObject.put("ifassigninstallman","1");
                        jsonObject.put("newpidate", install.getPidate());
                        jsonObject.put("newinstallman", assigneId);
                        jsonObject.put("remark", install.getRemark());
                        jsonObject.put("dlvitem", DataManager.batchInstallGoodsToJson(install.getIstitem()));
                        jsonArray.put(jsonObject);
                    } catch (Exception e3) {
                        exception = ConvertUtils.formatNull(e3.getMessage());
                        if(exception.equals("")) exception = "设置请求参数出错";
                        break;
                    }
                }
            }
            params.addBodyParameter("dlvdata", jsonArray.toString());
        }
        if(isNullDate){
            if(bar != null) bar.setVisibility(View.GONE);
            Toast.show(mContext, "批量数据中, 尚有未设置预约时间的项，请检查！", Toast.LENGTH_LONG);
        }else if(!exception.equals("")){
            if(bar != null) bar.setVisibility(View.GONE);
            Toast.show(mContext, exception, Toast.LENGTH_LONG);
        }else {
            postConfirmBatchPg(params);
        }
    }
    //打电话
    @Override
    public void onCall(String phone) {

    }
    //发短信
    @Override
    public void onSendMsg(String phone, String msg) {

    }
    //更新数据
    @Override
    public void updateListDatas(List<BatchPgListBean> listDatas) {
        dataList = listDatas;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.selectPeople = "";
        MyApplication.selectID = "";
    }
}
